package com.nervenets.template.controller.common;

import com.nervenets.general.entity.ResponseResult;
import com.nervenets.general.entity.Selection;
import com.nervenets.general.enumeration.Enums;
import com.nervenets.general.jwt.aspect.JwtSecurity;
import com.nervenets.general.web.BaseController;
import com.nervenets.general.web.params.DefaultTreeQueryParams;
import com.nervenets.template.controller.common.vo.DictVo;
import com.nervenets.template.service.DictService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.reflections.Reflections;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Api(value = "A常量", tags = "A常量")
@RestController
@RequestMapping("/api/constant")
public class ConstantController extends BaseController {
    @Resource
    private DictService dictService;

    @ApiOperation(value = "所有")
    @PostMapping({"/all"})
    @JwtSecurity(required = false)
    public ResponseEntity<ResponseResult<HashMap<String, List<Selection>>>> all() {
        HashMap<String, List<Selection>> o = new HashMap<>();

        Reflections reflections = new Reflections("com.nervenets.template.enumeration");
        Set<Class<? extends Enums>> types = reflections.getSubTypesOf(Enums.class);
        types.forEach(type -> o.put(type.getSimpleName(), getSelections(type.getEnumConstants())));

        HashMap<String, List<DictVo>> dictMap = new HashMap<>();
        dictService.getTrees(new DefaultTreeQueryParams<>()).forEach(dict ->
                Optional.ofNullable(dict.getChildren()).ifPresent(children ->
                        dictMap.put(dict.getCode(), dict.getChildren().stream().map(DictVo::new).collect(Collectors.toList()))));
        return successMessage(o, dictMap);
    }

    private List<Selection> getSelections(Enums[] enums) {
        return Arrays.stream(enums).map(e -> new Selection(e.getText(), e.getValue())).collect(Collectors.toList());
    }
}
